<?php

class TipManager extends Model_Abstract{
	public function add($tip = array())
	{
		$sql = "INSERT INTO `tip` SET `site_id`=?, `html_id`=?, `controller_view`=?, `font_size`=?, `font_color`=?, `bg_color`=?, `tip_width`=?, `tip_height`=?, `tip_padding`=?";
		try{
			return $this->_connection->execute($sql, $tip);
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function update($tip = array(), $id)
	{
		$sql = "UPDATE `tip` ";
		$setsql = array();
		$vars = array();
		foreach($tip as $k=>$v){
			$setsql[] = " `$k`=? ";
			$vars[] = $v;
		}
		if(!empty($setsql)){
			$sql .= ' SET ' . implode(' , ', $setsql);
		}
		$sql .= ' WHERE id=? ';
		$vars[] = $id;
		try{
			return $this->_connection->execute($sql, $vars);
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function getTipByFields($fields = array()){
		$sql = "SELECT tip.*, s.domain AS site FROM `tip` LEFT JOIN `sites` AS s ON tip.site_id=s.id ";
		$sqlshere = array();
		$vars = array();
		foreach($fields as $k=>$v){
			$sqlshere[] = " $k=? ";
			$vars[] = $v;
		}
		if(!empty($sqlshere)){
			$sql .= ' WHERE ' . implode(' AND ', $sqlshere);
		}
		try{
			$result = $this->_connection->query($sql, $vars);
			$tips = array();
			foreach($result as $r){
				$tips[$r['site']][$r['controller_view']][$r['html_id']] = $r;
			}

			return $tips;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
}




